import numpy as np
import tensorflow.compat.v2 as tf
tf.enable_v2_behavior()
import pandas as pd
from tensorflow import keras
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import RobustScaler
from sklearn.preprocessing import MinMaxScaler
from matplotlib import pyplot
import plotly.graph_objects as go
import math
import seaborn as sns
from sklearn.metrics import mean_squared_error
np.random.seed(1)
tf.random.set_seed(1)
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, LSTM, GRU, Dropout, RepeatVector, TimeDistributed
from keras import backend
MODELFILENAME = 'MODELS/GRU_3h_TFM_2c'
TIME_STEPS=18 #3h
CMODEL = GRU
MODEL = "GRU"
UNITS=43
DROPOUT1=0.118
DROPOUT2=0.243
ACTIVATION='tanh'
OPTIMIZER='adamax'
EPOCHS=56
BATCHSIZE=11
VALIDATIONSPLIT=0.1
# Code to read csv file into Colaboratory:
# from google.colab import files
# uploaded = files.upload()
# import io
# df = pd.read_csv(io.BytesIO(uploaded['SentDATA.csv']))
# Dataset is now stored in a Pandas Dataframe
df = pd.read_csv('../../data/dadesTFM.csv')
df.reset_index(inplace=True)
df['Time'] = pd.to_datetime(df['Time'])
df = df.set_index('Time')
columns = ['PM1','PM25','PM10','PM1ATM','PM25ATM','PM10ATM']
df1 = df.copy();
df1 = df1.rename(columns={"PM 1":"PM1","PM 2.5":"PM25","PM 10":"PM10","PM 1 ATM":"PM1ATM","PM 2.5 ATM":"PM25ATM","PM 10 ATM":"PM10ATM"})
df1['PM1'] = df['PM 1'].astype(np.float32)
df1['PM25'] = df['PM 2.5'].astype(np.float32)
df1['PM10'] = df['PM 10'].astype(np.float32)
df1['PM1ATM'] = df['PM 1 ATM'].astype(np.float32)
df1['PM25ATM'] = df['PM 2.5 ATM'].astype(np.float32)
df1['PM10ATM'] = df['PM 10 ATM'].astype(np.float32)
df2 = df1.copy()
train_size = int(len(df2) * 0.8)
test_size = len(df2) - train_size
train, test = df2.iloc[0:train_size], df2.iloc[train_size:len(df2)]
train.shape, test.shape
((3117, 7), (780, 7))
#Standardize the data
for col in columns:
scaler = StandardScaler()
train[col] = scaler.fit_transform(train[[col]])
<ipython-input-6-83cecdbc25f8>:4: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy train[col] = scaler.fit_transform(train[[col]]) <ipython-input-6-83cecdbc25f8>:4: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy train[col] = scaler.fit_transform(train[[col]]) <ipython-input-6-83cecdbc25f8>:4: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy train[col] = scaler.fit_transform(train[[col]]) <ipython-input-6-83cecdbc25f8>:4: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy train[col] = scaler.fit_transform(train[[col]]) <ipython-input-6-83cecdbc25f8>:4: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy train[col] = scaler.fit_transform(train[[col]]) <ipython-input-6-83cecdbc25f8>:4: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy train[col] = scaler.fit_transform(train[[col]])
def create_sequences(X, y, time_steps=TIME_STEPS):
Xs, ys = [], []
for i in range(len(X)-time_steps):
Xs.append(X.iloc[i:(i+time_steps)].values)
ys.append(y.iloc[i+time_steps])
return np.array(Xs), np.array(ys)
X_train, y_train = create_sequences(train[[columns[1]]], train[columns[1]])
#X_test, y_test = create_sequences(test[[columns[1]]], test[columns[1]])
print(f'X_train shape: {X_train.shape}')
print(f'y_train shape: {y_train.shape}')
X_train shape: (3099, 18, 1) y_train shape: (3099,)
#afegir nova mètrica
def rmse(y_true, y_pred):
return backend.sqrt(backend.mean(backend.square(y_pred - y_true), axis=-1))
model = Sequential()
model.add(CMODEL(units = UNITS, return_sequences=True, input_shape=(X_train.shape[1], X_train.shape[2])))
model.add(Dropout(rate=DROPOUT1))
model.add(CMODEL(units = UNITS, return_sequences=True))
model.add(Dropout(rate=DROPOUT2))
model.add(TimeDistributed(Dense(1,kernel_initializer='normal',activation=ACTIVATION)))
model.compile(optimizer=OPTIMIZER, loss='mae',metrics=['mse',rmse])
model.summary()
Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= gru (GRU) (None, 18, 43) 5934 _________________________________________________________________ dropout (Dropout) (None, 18, 43) 0 _________________________________________________________________ gru_1 (GRU) (None, 18, 43) 11352 _________________________________________________________________ dropout_1 (Dropout) (None, 18, 43) 0 _________________________________________________________________ time_distributed (TimeDistri (None, 18, 1) 44 ================================================================= Total params: 17,330 Trainable params: 17,330 Non-trainable params: 0 _________________________________________________________________
history = model.fit(X_train, y_train, epochs=EPOCHS, batch_size=BATCHSIZE, validation_split=VALIDATIONSPLIT,
callbacks=[keras.callbacks.EarlyStopping(monitor='val_loss', patience=5, mode='min')], shuffle=False)
Epoch 1/56 254/254 [==============================] - 7s 27ms/step - loss: 0.4937 - mse: 0.5358 - rmse: 0.5335 - val_loss: 0.1913 - val_mse: 0.0753 - val_rmse: 0.2556 Epoch 2/56 254/254 [==============================] - 5s 20ms/step - loss: 0.4417 - mse: 0.4471 - rmse: 0.4833 - val_loss: 0.1676 - val_mse: 0.0565 - val_rmse: 0.2122 Epoch 3/56 254/254 [==============================] - 5s 22ms/step - loss: 0.4302 - mse: 0.4335 - rmse: 0.4704 - val_loss: 0.1544 - val_mse: 0.0474 - val_rmse: 0.1860 Epoch 4/56 254/254 [==============================] - 6s 23ms/step - loss: 0.4246 - mse: 0.4265 - rmse: 0.4638 - val_loss: 0.1482 - val_mse: 0.0430 - val_rmse: 0.1710 Epoch 5/56 254/254 [==============================] - 6s 22ms/step - loss: 0.4211 - mse: 0.4228 - rmse: 0.4598 - val_loss: 0.1434 - val_mse: 0.0404 - val_rmse: 0.1604 Epoch 6/56 254/254 [==============================] - 6s 24ms/step - loss: 0.4185 - mse: 0.4202 - rmse: 0.4570 - val_loss: 0.1408 - val_mse: 0.0392 - val_rmse: 0.1543 Epoch 7/56 254/254 [==============================] - 6s 22ms/step - loss: 0.4171 - mse: 0.4187 - rmse: 0.4557 - val_loss: 0.1391 - val_mse: 0.0386 - val_rmse: 0.1508 Epoch 8/56 254/254 [==============================] - 5s 19ms/step - loss: 0.4157 - mse: 0.4174 - rmse: 0.4546 - val_loss: 0.1392 - val_mse: 0.0386 - val_rmse: 0.1501 Epoch 9/56 254/254 [==============================] - 5s 21ms/step - loss: 0.4154 - mse: 0.4172 - rmse: 0.4548 - val_loss: 0.1391 - val_mse: 0.0386 - val_rmse: 0.1496 Epoch 10/56 254/254 [==============================] - 5s 20ms/step - loss: 0.4148 - mse: 0.4170 - rmse: 0.4543 - val_loss: 0.1394 - val_mse: 0.0386 - val_rmse: 0.1497 Epoch 11/56 254/254 [==============================] - 5s 19ms/step - loss: 0.4150 - mse: 0.4163 - rmse: 0.4541 - val_loss: 0.1400 - val_mse: 0.0387 - val_rmse: 0.1502 Epoch 12/56 254/254 [==============================] - 5s 19ms/step - loss: 0.4149 - mse: 0.4165 - rmse: 0.4542 - val_loss: 0.1393 - val_mse: 0.0386 - val_rmse: 0.1494 Epoch 13/56 254/254 [==============================] - 5s 19ms/step - loss: 0.4147 - mse: 0.4161 - rmse: 0.4539 - val_loss: 0.1398 - val_mse: 0.0387 - val_rmse: 0.1499 Epoch 14/56 254/254 [==============================] - 6s 22ms/step - loss: 0.4146 - mse: 0.4163 - rmse: 0.4538 - val_loss: 0.1405 - val_mse: 0.0388 - val_rmse: 0.1505
import matplotlib.pyplot as plt
plt.plot(history.history['loss'], label='MAE Training loss')
plt.plot(history.history['val_loss'], label='MAE Validation loss')
plt.plot(history.history['mse'], label='MSE Training loss')
plt.plot(history.history['val_mse'], label='MSE Validation loss')
plt.plot(history.history['rmse'], label='RMSE Training loss')
plt.plot(history.history['val_rmse'], label='RMSE Validation loss')
plt.legend();
X_train_pred = model.predict(X_train, verbose=0)
train_mae_loss = np.mean(np.abs(X_train_pred - X_train), axis=1)
plt.hist(train_mae_loss, bins=50)
plt.xlabel('Train MAE loss')
plt.ylabel('Number of Samples');
def evaluate_prediction(predictions, actual, model_name):
errors = predictions - actual
mse = np.square(errors).mean()
rmse = np.sqrt(mse)
mae = np.abs(errors).mean()
print(model_name + ':')
print('Mean Absolute Error: {:.4f}'.format(mae))
print('Root Mean Square Error: {:.4f}'.format(rmse))
print('Mean Square Error: {:.4f}'.format(mse))
print('')
return mae,rmse,mse
mae,rmse,mse = evaluate_prediction(X_train_pred, X_train,MODEL)
GRU: Mean Absolute Error: 0.2304 Root Mean Square Error: 0.4475 Mean Square Error: 0.2003
model.save(MODELFILENAME+'.h5')
#càlcul del threshold de test
def calculate_threshold(X_test, X_test_pred):
distance = np.sqrt(np.mean(np.square(X_test_pred - X_test),axis=1))
"""Sorting the scores/diffs and using a 0.80 as cutoff value to pick the threshold"""
distance.sort();
cut_off = int(0.95 * len(distance));
threshold = distance[cut_off];
return threshold
for col in columns:
print ("####################### "+col +" ###########################")
#Standardize the test data
scaler = StandardScaler()
test_cpy = test.copy()
test[col] = scaler.fit_transform(test[[col]])
#creem seqüencia amb finestra temporal per les dades de test
X_test1, y_test1 = create_sequences(test[[col]], test[col])
print(f'Testing shape: {X_test1.shape}')
#evaluem el model
eval = model.evaluate(X_test1, y_test1)
print("evaluate: ",eval)
#predim el model
X_test1_pred = model.predict(X_test1, verbose=0)
evaluate_prediction(X_test1_pred, X_test1,MODEL)
#càlcul del mae_loss
test1_mae_loss = np.mean(np.abs(X_test1_pred - X_test1), axis=1)
test1_rmse_loss = np.sqrt(np.mean(np.square(X_test1_pred - X_test1),axis=1))
# reshaping test prediction
X_test1_predReshape = X_test1_pred.reshape((X_test1_pred.shape[0] * X_test1_pred.shape[1]), X_test1_pred.shape[2])
# reshaping test data
X_test1Reshape = X_test1.reshape((X_test1.shape[0] * X_test1.shape[1]), X_test1.shape[2])
threshold_test = calculate_threshold(X_test1Reshape,X_test1_predReshape)
test1_score_df = pd.DataFrame(test[TIME_STEPS:])
test1_score_df['loss'] = test1_rmse_loss.reshape((-1))
test1_score_df['threshold'] = threshold_test
test1_score_df['anomaly'] = test1_score_df['loss'] > test1_score_df['threshold']
test1_score_df[col] = test[TIME_STEPS:][col]
#gràfic test lost i threshold
fig = go.Figure()
fig.add_trace(go.Scatter(x=test1_score_df.index, y=test1_score_df['loss'], name='Test loss'))
fig.add_trace(go.Scatter(x=test1_score_df.index, y=test1_score_df['threshold'], name='Threshold'))
fig.update_layout(showlegend=True, title='Test loss vs. Threshold')
fig.show()
#Posem les anomalies en un array
anomalies1 = test1_score_df.loc[test1_score_df['anomaly'] == True]
anomalies1.shape
print('anomalies: ',anomalies1.shape); print();
#Gràfic dels punts i de les anomalíes amb els valors de dades transformades per verificar que la normalització que s'ha fet no distorssiona les dades
fig = go.Figure()
fig.add_trace(go.Scatter(x=test1_score_df.index, y=scaler.inverse_transform(test1_score_df[col]), name=col))
fig.add_trace(go.Scatter(x=anomalies1.index, y=scaler.inverse_transform(anomalies1[col]), mode='markers', name='Anomaly'))
fig.update_layout(showlegend=True, title='Detected anomalies')
fig.show()
print ("######################################################")
####################### PM1 ###########################
<ipython-input-17-e1f1d6df3b5c>:8: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy test[col] = scaler.fit_transform(test[[col]])
Testing shape: (762, 18, 1) 24/24 [==============================] - 0s 5ms/step - loss: 0.5171 - mse: 0.8488 - rmse: 0.5800 evaluate: [0.5171319246292114, 0.8488485813140869, 0.5800071954727173] GRU: Mean Absolute Error: 0.2466 Root Mean Square Error: 0.6019 Mean Square Error: 0.3623
anomalies: (59, 10)
###################################################### ####################### PM25 ###########################
<ipython-input-17-e1f1d6df3b5c>:8: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
Testing shape: (762, 18, 1) 24/24 [==============================] - 0s 4ms/step - loss: 0.5275 - mse: 0.7916 - rmse: 0.5906 evaluate: [0.5275145769119263, 0.7916497588157654, 0.5906068682670593] GRU: Mean Absolute Error: 0.2478 Root Mean Square Error: 0.5594 Mean Square Error: 0.3129
anomalies: (93, 10)
###################################################### ####################### PM10 ###########################
<ipython-input-17-e1f1d6df3b5c>:8: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
Testing shape: (762, 18, 1) 24/24 [==============================] - 0s 4ms/step - loss: 0.5316 - mse: 0.7665 - rmse: 0.5969 evaluate: [0.5316446423530579, 0.7664778828620911, 0.5968643426895142] GRU: Mean Absolute Error: 0.2463 Root Mean Square Error: 0.5221 Mean Square Error: 0.2725
anomalies: (52, 10)
###################################################### ####################### PM1ATM ###########################
<ipython-input-17-e1f1d6df3b5c>:8: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
Testing shape: (762, 18, 1) 24/24 [==============================] - 0s 4ms/step - loss: 0.5344 - mse: 0.7962 - rmse: 0.6034 evaluate: [0.5344480872154236, 0.7962043285369873, 0.6034378409385681] GRU: Mean Absolute Error: 0.2357 Root Mean Square Error: 0.5153 Mean Square Error: 0.2656
anomalies: (61, 10)
###################################################### ####################### PM25ATM ###########################
<ipython-input-17-e1f1d6df3b5c>:8: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
Testing shape: (762, 18, 1) 24/24 [==============================] - 0s 4ms/step - loss: 0.5322 - mse: 0.8019 - rmse: 0.6001 evaluate: [0.5321627259254456, 0.8019133806228638, 0.6000987887382507] GRU: Mean Absolute Error: 0.2362 Root Mean Square Error: 0.5275 Mean Square Error: 0.2783
anomalies: (61, 10)
###################################################### ####################### PM10ATM ###########################
<ipython-input-17-e1f1d6df3b5c>:8: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
Testing shape: (762, 18, 1) 24/24 [==============================] - 0s 5ms/step - loss: 0.5305 - mse: 0.7724 - rmse: 0.5951 evaluate: [0.5304937362670898, 0.7723891735076904, 0.5950577259063721] GRU: Mean Absolute Error: 0.2467 Root Mean Square Error: 0.5335 Mean Square Error: 0.2846
anomalies: (61, 10)
######################################################